<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2 class="dashboard-title">问卷管理</h2>
      <div class="dashboard-actions">
        <el-button
            type="primary"
            icon="el-icon-plus"
            @click="createNewSurvey"
            class="create-btn"
        >
          创建新问卷
        </el-button>
      </div>
    </div>

    <el-card class="welcome-card">
      <h3>欢迎回来，{{ authStore.currentUser?.username }}</h3>
      <p>创建、分发和分析您的调查问卷</p>
    </el-card>

    <el-card class="survey-list-card">
      <div class="survey-list-header">
        <h3>我的问卷</h3>
        <el-input
            v-model="searchQuery"
            placeholder="搜索问卷"
            clearable
            style="width: 300px"
            prefix-icon="el-icon-search"
            @clear="searchQuery = ''"
        />
      </div>

      <el-table
          :data="filteredSurveys"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
          empty-text="暂无问卷数据"
      >
        <el-table-column prop="title" label="问卷标题" width="250">
          <template #default="scope">
            <router-link
                :to="{ name: 'edit', params: { id: scope.row.id } }"
                class="survey-link"
            >
              {{ scope.row.title }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="submissions.length" label="提交数" width="120" align="center" />
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <el-button
                size="small"
                @click="editSurvey(scope.row.id)"
                icon="el-icon-edit"
                type="text"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="text"
                @click="viewResults(scope.row.id)"
                icon="el-icon-data-analysis"
                :disabled="scope.row.submissions.length === 0"
            >
              结果
            </el-button>
            <el-button
                size="small"
                type="text"
                @click="deleteSurvey(scope.row)"
                icon="el-icon-delete"
                style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useSurveyStore } from '@/store/modules/survey.store'
import { useAuthStore } from '@/store/modules/auth.store'

const router = useRouter()
const surveyStore = useSurveyStore()
const authStore = useAuthStore()
const surveys = ref<any[]>([])
const loading = ref(true)
const searchQuery = ref('')

onMounted(() => {
  loadSurveys()
})

const filteredSurveys = computed(() => {
  return surveys.value.filter(survey => {
    const query = searchQuery.value.toLowerCase()
    return (
        survey.title.toLowerCase().includes(query) ||
        (survey.description && survey.description.toLowerCase().includes(query))
    )
  })
})

const loadSurveys = async () => {
  try {
    loading.value = true
    // 模拟异步加载
    await new Promise(resolve => setTimeout(resolve, 500))
    surveys.value = [...surveyStore.surveys]
  } catch (error) {
    ElMessage.error('加载问卷列表失败')
    console.error('加载问卷错误:', error)
  } finally {
    loading.value = false
  }
}

const createNewSurvey = () => {
  const newId = surveyStore.createSurvey('新问卷')
  router.push({ name: 'edit', params: { id: newId } })
}

const editSurvey = (id: string) => {
  router.push({ name: 'edit', params: { id } })
}

const viewResults = (id: string) => {
  router.push({ name: 'results', params: { id } })
}

const deleteSurvey = async (survey: any) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除问卷 "${survey.title}" 吗?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const index = surveyStore.surveys.findIndex(s => s.id === survey.id)
    if (index !== -1) {
      surveyStore.surveys.splice(index, 1)
      surveyStore.saveSurveys()
      ElMessage.success('问卷已删除')
      loadSurveys()
    }
  } catch {
    // 用户取消了删除
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dashboard-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.create-btn {
  height: 40px;
  font-size: 14px;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #f5f7fa, #e4edf9);
  border: none;
  text-align: center;
}

.welcome-card h3 {
  color: #409eff;
  margin-bottom: 10px;
}

.welcome-card p {
  color: #606266;
  font-size: 14px;
}

.survey-list-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.survey-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.survey-list-header h3 {
  margin: 0;
  color: #303133;
}

.survey-link {
  color: #409eff;
  text-decoration: none;
  transition: color 0.3s;
}

.survey-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.el-table {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .survey-list-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .survey-list-header .el-input {
    width: 100%;
  }
}
</style>